import { ThunkAction } from "redux-thunk"
import { RootState } from ".."
import axios from "axios"
import useSelector from "../hooks"

export enum ActionTypes {
	FETCH_RECOMMEND_PRODUCTS_START,
	FETCH_RECOMMEND_PRODUCTS_SUCCESS,
	FETCH_RECOMMEND_PRODUCTS_FAILED,
}

interface FetchRecommendProductStartAction {
	type: typeof ActionTypes.FETCH_RECOMMEND_PRODUCTS_START
}

interface FetchRecommendProductSuccessAction {
	type: typeof ActionTypes.FETCH_RECOMMEND_PRODUCTS_SUCCESS
	payload: any
}

interface FetchRecommendProductFailedAction {
	type: typeof ActionTypes.FETCH_RECOMMEND_PRODUCTS_FAILED
	payload: any
}

export type RecommendProductAction = FetchRecommendProductStartAction | FetchRecommendProductSuccessAction | FetchRecommendProductFailedAction

export const fetchRecommendProductStartActionCreator = () => ({
	type: ActionTypes.FETCH_RECOMMEND_PRODUCTS_START,
})

export const fetchRecommendProductSuccessActionCreator = (data: any) => ({
	type: ActionTypes.FETCH_RECOMMEND_PRODUCTS_START,
	payload: data,
})

export const fetchRecommendProductFailedActionCreator = (err: any) => ({
	type: ActionTypes.FETCH_RECOMMEND_PRODUCTS_START,
	payload: err,
})

/**
 * ThunkAction<void, RootState, unknown, RecommendProductAction> 泛型说明
 * void 函数的返回类型
 * RootState state类型
 * unknown action额外参数类型
 * RecommendProductAction action类型
 */
export const getAsyncDataActionCreator = (): ThunkAction<void, RootState, unknown, RecommendProductAction> => async (dispatch, getState) => {
	axios
		.get("/productCollections")
		.then(res => {
			console.log("productCollections ==> res: ", res)
			dispatch(fetchRecommendProductSuccessActionCreator(res.data))
		})
		.catch(err => {
			console.log("productCollections ==> err: ", err)
			dispatch(fetchRecommendProductFailedActionCreator(err))
		})
}
